{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Collaborative Filtering RS with Alternating least squares"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pyspark.ml.evaluation import RegressionEvaluator\n",
    "from pyspark.ml.recommendation import ALS\n",
    "from pyspark.sql import Row"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "userId::movieId::rating::timestamp\n",
    "\n",
    "0::2::3::1424380312"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "lines = spark.read.text(\"sample_movielens_ratings.txt\").rdd\n",
    "\n",
    "parts = lines.map(lambda row: row.value.split(\"::\"))\n",
    "\n",
    "ratingsRDD = parts.map(lambda p: Row(userId=int(p[0]), movieId=int(p[1]),\n",
    "                                     rating=float(p[2]), timestamp=int(p[3])))\n",
    "                                     \n",
    "ratings = spark.createDataFrame(ratingsRDD)\n",
    "\n",
    "ratings.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "(training, test) = ratings.randomSplit([0.8, 0.2])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Build the recommendation model using ALS on the training data\n",
    "# Note we set cold start strategy to 'drop' to ensure we don't get NaN evaluation metrics\n",
    "als = ALS(maxIter=5, regParam=0.01, userCol=\"userId\", itemCol=\"movieId\", ratingCol=\"rating\",\n",
    "          coldStartStrategy=\"drop\")\n",
    "          \n",
    "model = als.fit(training)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Root-mean-square error = 1.7163276880851355\n"
     ]
    }
   ],
   "source": [
    "# Evaluate the model by computing the RMSE on the test data\n",
    "predictions = model.transform(test)\n",
    "evaluator = RegressionEvaluator(metricName=\"rmse\", labelCol=\"rating\",\n",
    "                                predictionCol=\"prediction\")\n",
    "rmse = evaluator.evaluate(predictions)\n",
    "print(\"Root-mean-square error = \" + str(rmse))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate top 10 movie recommendations for each user\n",
    "userRecs = model.recommendForAllUsers(10)\n",
    "# Generate top 10 user recommendations for each movie\n",
    "movieRecs = model.recommendForAllItems(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Apache Toree - PySpark",
   "language": "python",
   "name": "apache_toree_pyspark"
  },
  "language_info": {
   "codemirror_mode": "text/x-ipython",
   "file_extension": ".py",
   "mimetype": "text/x-ipython",
   "name": "python",
   "pygments_lexer": "python",
   "version": "3.6.3\n"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
